const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");
const compression = require("compression");

// 导入配置和中间件
const config = require("./config/config");
const { errorHandler, notFound } = require("./middleware/errorHandler");
require("./model");
// 创建Express应用
const app = express();

// 安全中间件
app.use(helmet());

// 跨域中间件
app.use(cors());

// 压缩中间件
app.use(compression());

// 日志中间件
app.use(morgan("dev"));

// 请求体解析中间件
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));

// 路由
app.use("/", require("./router"));

// 404处理
app.use(notFound);

// 全局错误处理
app.use(errorHandler);

// 启动服务器
const PORT = config.server.port;

app.listen(PORT, () => {
  console.log(`🚀 Server is running on port ${PORT}`);
  console.log(`📅 时间: ${new Date().toLocaleString()}`);
  console.log(`🌍 Environment: ${config.server.env}`);
});

module.exports = app;
